package com.xudow.app.db.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xudow.app.model.LocalMessage;
import com.xudow.app.util.DateUtil;
import com.xudow.app.util.Lists;
import com.xudow.app.util.TimeUtils;

import java.util.Date;
import java.util.List;

/**
 * 消息DAO
 *
 * @author lukecheng
 */
public class MessageDao {

    /**
     * 每页显示条数
     */
    private static final int DEFAULT_LIMIT = 10;

    private SQLiteDatabase db;

    public MessageDao(SQLiteDatabase db) {
        this.db = db;
    }

    public void insertMessage(LocalMessage msg) {
        //判断消息是否已经存在
        if (isMessageExists(msg)) {
            return;
        }

        ContentValues cv = new ContentValues();
        cv.put("user_id", msg.getUserId());
        cv.put("message_id", msg.getMessageId());
        cv.put("title", msg.getTitle());
        if (null != msg.getContent()) {
            cv.put("content", msg.getContent());
        }
        cv.put("channel", msg.getChannel());
        cv.put("create_time", TimeUtils.date2str(msg.getCreateTime(), TimeUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS));
        cv.put("status", msg.getStatus());
        cv.put("is_system_msg", msg.getIsSystemMessage());

        db.insert(LocalMessage.TABLE_NAME, null, cv);
    }

    /**
     * 获取db里面的消息
     *
     * @param userId 用户id
     * @param isHome 是否首页显示(首页只显示0,1， 我的消息显示: 1,2)
     * @return
     */
    public List<LocalMessage> getMessages(long userId, boolean isHome, Date startTime) {
        List<LocalMessage> messages = Lists.newArrayList();

        StringBuilder selection = new StringBuilder("user_id=?");
        List<String> selectionArgs = Lists.newArrayList();
        selectionArgs.add(Long.toString(userId));

        if (isHome) {
            selection.append(" AND is_system_msg IN (?, ?) ");
            selectionArgs.add(Integer.toString(LocalMessage.MSG_TYPE_COMMON));
            selectionArgs.add(Integer.toString(LocalMessage.MSG_TYPE_SYSTEM));
        } else {
            selection.append(" AND is_system_msg IN (?, ?)");
            selectionArgs.add(Integer.toString(LocalMessage.MSG_TYPE_OA));
            selectionArgs.add(Integer.toString(LocalMessage.MSG_TYPE_SYSTEM));
        }

        if (null != startTime) {
            String startTimeStr = DateUtil.dateTimeToStr(startTime, DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);

            selection.append(" AND create_time<?");
            selectionArgs.add(startTimeStr);
        }

        Cursor cursor = db.query(LocalMessage.TABLE_NAME,
                new String[]{"message_id", "title", "content", "channel", "create_time", "status", "is_system_msg", "agency_name"},
                selection.toString(),
                selectionArgs.toArray(new String[selectionArgs.size()]),
                null,
                null,
                "create_time DESC",
                Integer.toString(DEFAULT_LIMIT));

        while (cursor.moveToNext()) {
            long messageId = cursor.getInt(cursor.getColumnIndex("message_id"));
            String title = cursor.getString(cursor.getColumnIndex("title"));
            String content = cursor.getString(cursor.getColumnIndex("content"));
            int channel = cursor.getInt(cursor.getColumnIndex("channel"));
            String createTimeStr = cursor.getString(cursor.getColumnIndex("create_time"));
            int status = cursor.getInt(cursor.getColumnIndex("status"));
            int isSystemMessage = cursor.getInt(cursor.getColumnIndex("is_system_msg"));
            String agencyName = cursor.getString(cursor.getColumnIndex("agency_name"));

            Date createDate = DateUtil.strToDateTime(createTimeStr, DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);

            LocalMessage msg = new LocalMessage();
            msg.setUserId(userId);
            msg.setTitle(title);
            msg.setStatus(status);
            msg.setMessageId(messageId);
            msg.setAgencyName(agencyName);
            msg.setChannel(channel);
            msg.setContent(content);
            msg.setIsSystemMessage(isSystemMessage);
            msg.setCreateTime(createDate);

            messages.add(msg);
        }

        cursor.close();

        return messages;
    }

    /**
     * 判断消息是否已存在
     *
     * @param msg
     * @return
     */
    private boolean isMessageExists(LocalMessage msg) {
        Cursor cursor = db.query(LocalMessage.TABLE_NAME,
                new String[]{"_id"},
                "user_id=? AND message_id=? AND is_system_msg=?",
                new String[]{
                        Long.toString(msg.getUserId()),
                        Long.toString(msg.getMessageId()),
                        Integer.toString(msg.getIsSystemMessage())
                },
                null,
                null,
                "create_time DESC");

        boolean ret = false;
        if (cursor.getCount() > 0) {
            ret = true;
        }

        cursor.close();

        return ret;
    }

}
